from django.db.models import Q
from rest_framework.filters import BaseFilterBackend

from user.models import Department


class MedicineFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        name = request.query_params.get('name', None)
        department = request.query_params.get('department', None)  # [1, 2]
        print(name, type(name))
        import ast
        # 定义包含列表形式的字符串
        department_str = department
        # 使用ast.literal_eval()将字符串转换为列表
        department_list = ast.literal_eval(department_str)
        print(department_list)  # 输出: [4, 5, 6]
        print(department_list, type(department_list))

        for depar in department_list:
            print(depar)
            department_obj = Department.objects.all().filter(id=depar).first()
            print(department_obj)
            queryset = queryset.filter(name__icontains=name, department__name__icontains=department_obj.name)
            return queryset


class DepartFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        name = request.query_params.get('name', None)
        depart_type = request.query_params.get('depart_type', None)
        queryset = queryset.filter(name__icontains=name, depart_type__icontains=depart_type)
        return queryset


class MyFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        name = request.query_params.get('name', None)
        depart_type = request.query_params.get('depart_type', None)
        if name:
            queryset = queryset.filter(name__icontains=name)
        if depart_type:
            queryset = queryset.filter(depart_type=depart_type)
        return queryset
